import Cocoa
import FlutterMacOS
import NetworkExtension

/**
 * VPN 插件 - macOS 平台实现
 * 提供与 V2Ray/Xray 核心的交互接口
 */
public class VpnPlugin: NSObject, FlutterPlugin {
    
    private var xrayProcess: Process?
    private var vpnManager: NEVPNManager?
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "com.fimuer.vpn/core", binaryMessenger: registrar.messenger)
        let instance = VpnPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "startXray":
            if let args = call.arguments as? [String: Any],
               let config = args["config"] as? String {
                startXray(config: config, result: result)
            } else {
                result(FlutterError(code: "INVALID_ARGUMENT", message: "Config is required", details: nil))
            }
            
        case "stopXray":
            stopXray(result: result)
            
        case "getTrafficStats":
            getTrafficStats(result: result)
            
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    /**
     * 启动 Xray 核心
     */
    private func startXray(config: String, result: @escaping FlutterResult) {
        // 1. 写入配置文件
        guard let configData = config.data(using: .utf8) else {
            result(FlutterError(code: "ENCODING_ERROR", message: "Failed to encode config", details: nil))
            return
        }
        
        let fileManager = FileManager.default
        let tempDir = NSTemporaryDirectory()
        let configURL = URL(fileURLWithPath: tempDir).appendingPathComponent("xray_config.json")
        
        do {
            try configData.write(to: configURL)
            print("Config written to: \(configURL.path)")
        } catch {
            result(FlutterError(code: "WRITE_ERROR", message: "Failed to write config: \(error.localizedDescription)", details: nil))
            return
        }
        
        // 2. 查找 xray 可执行文件
        let possiblePaths = [
            "./xray-core/xray",
            "./xray",
            "/usr/local/bin/xray",
            "/opt/homebrew/bin/xray",
            "/usr/bin/xray"
        ]
        
        var xrayPath: String?
        for path in possiblePaths {
            if fileManager.isExecutableFile(atPath: path) {
                xrayPath = path
                break
            }
        }
        
        guard let xrayExecutable = xrayPath else {
            result(FlutterError(code: "NOT_FOUND", message: "Xray executable not found", details: nil))
            return
        }
        
        print("Found xray at: \(xrayExecutable)")
        
        // 3. 启动 xray 进程
        let process = Process()
        process.executableURL = URL(fileURLWithPath: xrayExecutable)
        process.arguments = ["run", "-config", configURL.path]
        
        // 设置输出管道以便调试
        let outputPipe = Pipe()
        let errorPipe = Pipe()
        process.standardOutput = outputPipe
        process.standardError = errorPipe
        
        // 异步读取输出
        outputPipe.fileHandleForReading.readabilityHandler = { handle in
            if let output = String(data: handle.availableData, encoding: .utf8), !output.isEmpty {
                print("Xray output: \(output)")
            }
        }
        
        errorPipe.fileHandleForReading.readabilityHandler = { handle in
            if let error = String(data: handle.availableData, encoding: .utf8), !error.isEmpty {
                print("Xray error: \(error)")
            }
        }
        
        do {
            try process.run()
            self.xrayProcess = process
            print("Xray started successfully with PID: \(process.processIdentifier)")
            result(true)
        } catch {
            result(FlutterError(code: "START_ERROR", message: "Failed to start Xray: \(error.localizedDescription)", details: nil))
        }
    }
    
    /**
     * 停止 Xray 核心
     */
    private func stopXray(result: @escaping FlutterResult) {
        if let process = xrayProcess {
            if process.isRunning {
                print("Stopping Xray process (PID: \(process.processIdentifier))")
                process.terminate()
                
                // 等待进程退出
                DispatchQueue.global().async {
                    process.waitUntilExit()
                    DispatchQueue.main.async {
                        print("Xray stopped successfully")
                        self.xrayProcess = nil
                        result(true)
                    }
                }
            } else {
                xrayProcess = nil
                result(true)
            }
        } else {
            result(true)
        }
    }
    
    /**
     * 获取流量统计
     */
    private func getTrafficStats(result: @escaping FlutterResult) {
        // 从进程获取流量统计（需要 xray 提供 API）
        let stats: [String: Int] = [
            "uploadSpeed": 0,
            "downloadSpeed": 0,
            "totalUpload": 0,
            "totalDownload": 0
        ]
        result(stats)
    }
    
    deinit {
        // 清理：停止 xray 进程
        if let process = xrayProcess, process.isRunning {
            process.terminate()
        }
    }
}
